package com.jevons.muffin.net.observable;

import android.util.Log;


import com.jevons.muffin.net.RetrofitServiceManager;
import com.jevons.muffin.net.bean.DownloadResponse;

import java.io.File;
import java.io.InputStream;
import java.io.RandomAccessFile;

import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.annotations.NonNull;
import okhttp3.Call;
import okhttp3.Request;
import okhttp3.ResponseBody;

/**
 * 文件下载回调
 * @author linaisheng
 * Created at 2019/3/27.
 */

public class DownloadObservable implements ObservableOnSubscribe<DownloadResponse> {

    private static final String TAG = DownloadObservable.class.getSimpleName();

    //文件保存路径
    private String saveFilePath;
    //返回体
    private ResponseBody responseBody;

    public DownloadObservable(String saveFilePath, ResponseBody responseBody) {
        this.saveFilePath = saveFilePath;
        this.responseBody =responseBody;
    }

    @Override
    public void subscribe(@NonNull ObservableEmitter<DownloadResponse> emitter) throws Exception {
        retrofitDownload(emitter);
    }

    /**
     * retrofit方式下载
     * @param emitter
     */
    private void retrofitDownload(ObservableEmitter<DownloadResponse> emitter) {
        File saveFile = new File(saveFilePath);
        if (saveFile.exists()) {
            boolean isDelete = saveFile.delete();
            Log.w(TAG, "file exists to be delete:" + isDelete);
        }

        RandomAccessFile randomAccessFile = null;
        InputStream inputStream = null;
        long total = 0;
        try {
            byte[] buf = new byte[2048];
            int len = 0;
            long responseLength = responseBody.contentLength();
            inputStream = responseBody.byteStream();
            File dir = saveFile.getParentFile();
            if (!dir.exists()) {
                dir.mkdirs();
            }
            randomAccessFile = new RandomAccessFile(saveFile, "rwd");
            //能获取文件大小时，直接赋值文件大小
            if (responseLength >  0) {
                randomAccessFile.setLength(responseLength);
            }
            int progress = 0;
            int lastProgress = -1;
            while ((len = inputStream.read(buf)) != -1) {
                randomAccessFile.write(buf, 0, len);
                total += len;
                //只有在获取文件大小时才能计算下载进度
                if (responseLength > 0) {
                    lastProgress = progress;
                    progress = (int) (total * 100 / responseLength);
                    if (progress >= 0 && progress != lastProgress) {
                        emitter.onNext(new DownloadResponse(saveFilePath, DownloadResponse.Type.PROGRESS,
                                String.valueOf(progress)));
                    }
                } else if (progress != lastProgress) {
                    lastProgress = progress;
                    emitter.onNext(new DownloadResponse(saveFilePath, DownloadResponse.Type.PROGRESS,
                            String.valueOf(progress)));
                }
            }
            //当无法获取下载文件大小时，在下载完成后进行设置文件大小
            if (responseLength <= 0) {
                randomAccessFile.setLength(total);
            }
            emitter.onNext(new DownloadResponse(saveFilePath, DownloadResponse.Type.SUCCESS,
                    saveFile.getAbsolutePath()));
        } catch (Exception e) {
            emitter.onNext(new DownloadResponse(saveFilePath,
                    DownloadResponse.Type.ERROR, e.getMessage()));
            e.printStackTrace();
        } finally {
            try {
                if (randomAccessFile != null) {
                    randomAccessFile.close();
                }

                if (inputStream != null) {
                    inputStream.close();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }


}
